﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InfoStuffStore.Common;

namespace InfoStuffStore
{
    public partial class FormViewBlog : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadBlog();
                LoadComments();
            }
        }

        private void LoadComments()
        {
            if (Request.QueryString.AllKeys.Contains("blogid"))
            {
                int blogid = Convert.ToInt32(Request.QueryString["blogid"]);

                using (DBDataContext dataContext = new DBDataContext())
                {
                    var result = dataContext.BlogComments.Where(obj => (obj.BlogID == blogid));
                    GridBlogComments.DataSource = result;
                    GridBlogComments.DataBind();
                }
            }
        }

        private void LoadBlog()
        {
            if (Request.QueryString.AllKeys.Contains("blogid"))
            {
                int blogid = Convert.ToInt32(Request.QueryString["blogid"]);
                using (DBDataContext dataContext = new DBDataContext())
                {
                    var result = dataContext.Blogs.Where(obj => (obj.BlogID == blogid));
                    foreach (var item in result)
                    {
                        h2Title.InnerHtml = item.Title;
                        blogDesc.InnerHtml = item.BlogText;
                    }
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Request.QueryString.AllKeys.Contains("blogid"))
            {
                int blogid = Convert.ToInt32(Request.QueryString["blogid"]);

                using (DBDataContext dataContext = new DBDataContext())
                {
                    BlogComment comment = new BlogComment()
                    {
                        BlogID = blogid,
                        CommentText = txtComment.Text,
                        EmailID = txtEmailID.Text,
                        Name = txtName.Text,
                        CreatedDate = DateTime.Now
                    };

                    dataContext.BlogComments.InsertOnSubmit(comment);
                    dataContext.SubmitChanges();

                    var result = dataContext.BlogComments.Where(obj => (obj.BlogID == blogid));
                    GridBlogComments.DataSource = result;
                    GridBlogComments.DataBind();
                }
            }
        }
    }
}